package com.yoda.mall.mysql.api;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yoda.common.exception.BusinessException;
import com.yoda.mall.api.RoleResourceRelationApi;
import com.yoda.mall.model.entity.ums.Menu;
import com.yoda.mall.model.entity.ums.RoleMenuRelation;
import com.yoda.mall.model.entity.ums.RoleResourceRelation;
import com.yoda.mall.mysql.mapper.MenuMapper;
import com.yoda.mall.mysql.mapper.RoleResourceRelationMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import javax.annotation.Resource;
import java.util.List;

@DubboService
public class RoleResourceRelationApiImpl implements RoleResourceRelationApi {
    @Resource
    private RoleResourceRelationMapper roleResourceRelationMapper;
    @Resource
    private MenuMapper menuMapper;
    @Override
    public List<Menu> listResourceByRoleId(Integer roleId) {
        LambdaQueryWrapper<RoleResourceRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleResourceRelation::getRoleId,roleId);
        List<RoleResourceRelation> roleResourceRelations = roleResourceRelationMapper.selectList(wrapper);
        if(CollUtil.isEmpty(roleResourceRelations)){
            return null;
        }
        List<Long> menuIdList = CollUtil.getFieldValues(roleResourceRelations,"resourceId",Long.class);
        LambdaQueryWrapper<Menu> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(Menu::getId,menuIdList).orderByAsc(Menu::getId);
        return menuMapper.selectList(wrapper1);
    }

    @Override
    public void deleteByRoleId(int id) {
        LambdaQueryWrapper<RoleResourceRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleResourceRelation::getRoleId,id);
        roleResourceRelationMapper.delete(wrapper);
    }

    @Override
    public void save(RoleResourceRelation roleResourceRelation) {
        roleResourceRelationMapper.insert(roleResourceRelation);
    }

    @Override
    public void deleteByResourceId(Integer id) {
        LambdaQueryWrapper<RoleResourceRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleResourceRelation::getResourceId,id);
        roleResourceRelationMapper.delete(wrapper);
    }
}